import { createRouter, createWebHistory } from 'vue-router';
import auth from '@/common/auth';

// store
import pinia from '@/store/store';
import useStore from '@/store/index';

// 进度条
import nprogress from '@/common/nprogress/index';
import { routes, staticRoutes, noFound } from './routes';

const router = createRouter({
  history: createWebHistory(),
  routes: staticRoutes,
  scrollBehavior: (to, from, savedPosition) => {
    if (savedPosition) {
      return savedPosition;
    } else {
      return { top: 0 };
    }
  },
});

// 路由守卫
const whiteList = ['/login', '/404'];
const isWhitePage = (path: string): boolean => whiteList.indexOf(path) !== -1;

let isRouteComplete = false; // 判断动态路由是否已经被获取
router.beforeEach((to, from, next) => {
  nprogress.start();
  // 为了外部js使用pinia，单独创建store.ts以便外部js引用。但是持久化失效，于是在路由钩子中注册一下解决。
  const store = useStore(pinia);
  if (isWhitePage(to.path)) {
    if (to.path == '/login' && auth.getToken()) {
      next('/');
    } else {
      next();
    }
  } else {
    const apiMenuList: any = store.getApiMenus;
    const routerMenu = store.routerMenu;
    const storeMenus = store.getMenus;
    const token = store.getToken;

    if (!storeMenus || !storeMenus.length) {
      isRouteComplete = false;
    }

    if (!token || !apiMenuList.length) {
      // 先判断token和是否已生成过权限菜单
      next({ path: '/login', replace: true });
    } else {
      if (!isRouteComplete) {
        // 动态添加路由
        let menuRes: any[] = [];
        routerMenu.forEach((item: any) => {
          routes.forEach((it: any) => {
            if (it.path == item.path) {
              menuRes.push(it);
            }
          });
        });
        // 将404添加进去.原因是：作为一级路由，当刷新，动态路由还未加载，路由就已经做了匹配，找不到就跳到了404
        if (menuRes[menuRes.length - 1].path != '/:catchAll(.*)') {
          menuRes.push(noFound);
        }
        // 添加动态路由
        menuRes.forEach((item: any) => {
          // 动态向layout中添加子路由。实现路由嵌套！！！
          router.addRoute('layout', item);
        });
        // 把校验过的动态菜单进行保存
        store.setMenu(menuRes);
        isRouteComplete = true;
        //确保addRoute()时动态添加的路由已经被完全加载上去
        next({
          path: to.path,
          replace: true,
        });
      } else {
        // 筛选出当前要跳转路由的所有权限menuCode。用来控制当前页按钮、功能块的显隐
        let menuCode: any = [];
        apiMenuList.forEach((el: any) => {
          // 当前页
          if (el.path == to.path) {
            const mapCurMenuCode = (list: []) => {
              list.forEach((item: any) => {
                menuCode.push(item.menuCode);
                if (item.childrenList && item.childrenList.length) {
                  mapCurMenuCode(item.childrenList);
                }
              });
            };

            if (el.childrenList && el.childrenList.length) {
              mapCurMenuCode(el.childrenList);
              store.setCurrentMenuCode(menuCode);
            } else {
              store.setCurrentMenuCode([]);
            }
          }
        });

        next();
      }
    }
  }
});

// 路由加载结束后执行
router.afterEach((to) => {
  nprogress.close();
  // 设置浏览器页面标题
  if (to.meta.title) {
    document.title = String(to.meta.title);
  }
});

export default router;
